﻿Imports System.ComponentModel

Public Class frmSysManageUsers

    Private m_curUser As ClsUser = Nothing  '当前选中的用户数据，默认为nothing
    Private m_userList As List(Of ClsUser)
    Private m_state As Int16 = 0  '编辑状态：0-浏览 1-新增 2-编辑 3-保存
    Private m_row As Int32 = -1 '当前选择行，默认为-1
    Private m_saving As Boolean = False  '当前是否正在保存
    Private m_dirty As Boolean = False  '当前编辑中的数据是否变化
    Private m_broker As ClsBroker = New ClsBroker()

    ''' <summary>
    ''' 自定义文本框控件的内容改变事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub MoniteTextChange(ByVal sender As Object, ByVal e As CustomControlChangeNotifyEventArg)
        If m_state > 0 Then
            m_dirty = True
            Me.btnSaveUser.Enabled = True
        End If

        '检查当前控件状态
        'CheckCurrentState()
    End Sub

    Private Sub CheckCurrentState()
        '检查按钮
        CheckButtonState()

        '检查文本框
        CheckTextState()
    End Sub

    Private Sub CheckTextState()
        Select Case m_state
            Case 0
                If m_curUser IsNot Nothing Then
                    Me.txtUserName.Text = m_curUser.UserName
                    Me.txtUserPass.Text = m_curUser.UserPassword
                    Me.txtUserId.Text = m_curUser.UserId
                    Me.chkIfAdmin.Checked = m_curUser.UserIfAdmin
                Else
                    Me.txtUserName.Text = ""
                    Me.txtUserPass.Text = ""
                    Me.txtUserId.Text = ""
                    Me.chkIfAdmin.Checked = False
                End If
                Me.txtUserName.ReadOnly = True
                Me.txtUserPass.ReadOnly = True
            Case 1
                '判断是否正在修改中
                'If Not m_dirty Then

                Me.txtUserName.Text = ""
                    Me.txtUserPass.Text = ""
                    Me.txtUserId.Text = ""
                    Me.chkIfAdmin.Checked = False

                'End If

                Me.txtUserName.ReadOnly = False
                Me.txtUserPass.ReadOnly = False

            Case 2
                If m_curUser IsNot Nothing Then
                    Me.txtUserName.Text = m_curUser.UserName
                    '密码置空，则表示不修改。
                    Me.txtUserPass.Text = "" 'm_curUser.UserPassword
                    Me.txtUserId.Text = m_curUser.UserId
                    Me.chkIfAdmin.Checked = m_curUser.UserIfAdmin
                End If
                Me.txtUserName.ReadOnly = False
                Me.txtUserPass.ReadOnly = False '编辑时密码不可修改
            Case 3
                Me.txtUserName.ReadOnly = True
                Me.txtUserPass.ReadOnly = True
        End Select
    End Sub

    Private Sub CheckButtonState()

        Select Case m_state
            Case 0
                Me.btnAddUser.Enabled = True
                Me.btnModifyUser.Enabled = True
                Me.btnSaveUser.Enabled = False
                Me.btnDeleteUser.Enabled = IIf(m_curUser Is Nothing, False, True)
                Me.btnClose.Enabled = True

                Me.btnAddUser.Text = "新建"
                Me.btnModifyUser.Text = "编辑"
            Case 1
                Me.btnAddUser.Enabled = True
                Me.btnModifyUser.Enabled = False
                Me.btnSaveUser.Enabled = IIf(m_dirty, False, True)
                Me.btnDeleteUser.Enabled = False
                Me.btnClose.Enabled = True

                Me.btnAddUser.Text = "取消新建"
                'Me.btnModifyUser.Text = "编辑"
            Case 2
                Me.btnAddUser.Enabled = False
                Me.btnModifyUser.Enabled = True
                Me.btnSaveUser.Enabled = IIf(m_dirty, False, True)
                Me.btnDeleteUser.Enabled = False
                Me.btnClose.Enabled = True

                'Me.btnAddUser.Text = "取消新建"
                Me.btnModifyUser.Text = "取消编辑"
            Case 3
                Me.btnAddUser.Enabled = False
                Me.btnModifyUser.Enabled = False
                Me.btnSaveUser.Enabled = False
                Me.btnDeleteUser.Enabled = False
                Me.btnClose.Enabled = False
                Me.btnAddUser.Text = "新建"
                Me.btnModifyUser.Text = "编辑"
        End Select

    End Sub

    Private Sub InitialListViewHeader()
        '设置列表格式
        With Me.lstUsers
            .View = View.Details
            .FullRowSelect = True
            .MultiSelect = False
            .Width = Me.FlowLayoutPanel1.Width  '宽度占满窗体
            .HeaderStyle = ColumnHeaderStyle.Nonclickable '标题不可点击
            .GridLines = True
        End With

        '设置表头
        Dim headers(3) As ColumnHeader
        Dim header1 As ColumnHeader = New ColumnHeader()
        With header1
            .Text = "编号"
            .Name = "hId"
            .Width = 40
            .TextAlign = HorizontalAlignment.Center

        End With

        Dim header2 As ColumnHeader = New ColumnHeader()
        With header2
            .Text = "登录名称"
            .Name = "hName"
            .Width = 120
            .TextAlign = HorizontalAlignment.Left
        End With

        Dim header3 As ColumnHeader = New ColumnHeader()
        With header3
            .Text = "登录密码"
            .Name = "hPass"
            .Width = 200
            .TextAlign = HorizontalAlignment.Center
        End With

        Dim header4 As ColumnHeader = New ColumnHeader()
        With header4
            .Text = "管理员"
            .Name = "hAdmin"
            .Width = 60
            .TextAlign = HorizontalAlignment.Center
        End With
        headers(0) = header1
        headers(1) = header2
        headers(2) = header3
        headers(3) = header4

        Me.lstUsers.Columns.AddRange(headers)

    End Sub

    Private Sub LoadUserData()
        Try
            Dim tmpUserDb As ClsUserDbAccess = New ClsUserDbAccess(sysAppInfoConnectionString)
            m_userList = tmpUserDb.GetAllUser()

        Catch ex As Exception
            mErrorCreater = "frmSysManageUser - LoadUserData"
            mErrorMessage = ex.Message
            mErrorNumber = -2005
        End Try

    End Sub

    Private Sub LoadDataToListView()
        If m_userList Is Nothing Then
            Return
        End If
        Dim tmpItem As ListViewItem '= New ListViewItem()
        For Each tu As ClsUser In m_userList
            tmpItem = New ListViewItem()
            tmpItem.Text = tu.UserId.ToString()
            tmpItem.SubItems.Add(tu.UserName)
            tmpItem.SubItems.Add(tu.UserPassword)
            tmpItem.SubItems.Add(IIf(tu.UserIfAdmin, "是", "否"))

            Me.lstUsers.Items.Add(tmpItem)
        Next
    End Sub

    Private Sub frmSysManageUsers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '添加回调监控文本内容修改
        AddHandler ClsBroker.OnCustomCtrolContentChange, AddressOf MoniteTextChange
        '加载表格头
        InitialListViewHeader()
        '加载数据
        LoadUserData()
        '加载数据到表格
        LoadDataToListView()
        '状态
        m_state = 0

        CheckCurrentState()
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub frmSysManageUsers_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        RemoveHandler ClsBroker.OnCustomCtrolContentChange, AddressOf MoniteTextChange
    End Sub

    Private Sub lstUsers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstUsers.SelectedIndexChanged
        '取出当前列表选择行，并更新
        If Not SelectedToUser() Then
            Return
        End If

        '将当前对象值填充到控件上
        UserToControl()

        '检查控件状态
        CheckCurrentState()
    End Sub

    Private Function SelectedToUser() As Boolean
        '取出当前选择行
        Dim selItem As ListView.SelectedListViewItemCollection = Me.lstUsers.SelectedItems

        If selItem.Count < 1 Then
            m_row = -1
            m_curUser = Nothing
            Return False
        Else
            m_row = selItem.Item(0).Index
            m_curUser = m_userList.Item(m_row)

            Return True
        End If

    End Function

    Private Sub UserToControl()
        '填充控件内容
        If m_curUser Is Nothing Then
            Return
        End If

        Me.txtUserId.Text = m_curUser.UserId
        Me.txtUserName.Text = m_curUser.UserName

        If m_state = 2 Then
            Me.txtUserPass.Text = ""
        Else
            Me.txtUserPass.Text = m_curUser.UserPassword

        End If

        Me.chkIfAdmin.Checked = m_curUser.UserIfAdmin
    End Sub

    Private Sub ControlToUser()


        '填充控件内容
        If m_curUser Is Nothing Then
            m_curUser = New ClsUser()
        End If

        If m_state = 1 Then
            m_curUser.UserId = 0
        Else
            m_curUser.UserId = Integer.Parse(Me.txtUserId.Text)
        End If
        m_curUser.UserName = Me.txtUserName.Text
        m_curUser.UserIfAdmin = Me.chkIfAdmin.Checked
        '判断是否是新建，如果是新建，则密码要先加密
        If m_state = 1 Then
            m_curUser.UserPassword = Md5Encrypt(Me.txtUserPass.Text.Trim())
        Else
            '编辑时判断密码框是否置空
            If Not String.IsNullOrEmpty(Me.txtUserPass.Text.Trim()) Then
                m_curUser.UserPassword = Md5Encrypt(Me.txtUserPass.Text.Trim())
            End If
            'm_curUser.UserPassword = Me.txtUserPass.Text
        End If
    End Sub

    Private Sub btnAddUser_Click(sender As Object, e As EventArgs) Handles btnAddUser.Click
        '点击新建
        '判断是否已是新建状态
        If m_state = 1 Then
            '取消新建状态
            m_state = 0

            '将当前user填充到控件
            UserToControl()

            'Return
        End If

        If m_state = 0 Then
            'Return
            m_state = 1
        End If

        CheckCurrentState()

    End Sub

    Private Sub btnModifyUser_Click(sender As Object, e As EventArgs) Handles btnModifyUser.Click
        '判断是否已在编辑状态
        If m_state = 2 Then
            '取消编辑状态
            m_state = 0
            'user内容填充control
            UserToControl()
        Else
            m_state = 2
        End If

        'If m_state = 0 Then
        'End If

        CheckCurrentState()
    End Sub

    Private Sub btnSaveUser_Click(sender As Object, e As EventArgs) Handles btnSaveUser.Click
        '判断是否处于编辑或新建中
        If m_state = 0 Then
            Return
        End If

        '验证内容是否合格
        If Not ValidControlContent() Then
            MessageBox.Show("用户名或密码不正确。或用户名已经存在。", "用户管理")
            Return
        End If

        '控件内容到user
        ControlToUser()

        '保存当前内容到库中
        SaveUserToDb()
    End Sub

    Private Function ValidControlContent() As Boolean
        '验证当前控件内容是否正确
        Dim tmpName As String = Me.txtUserName.Text.Trim()
        Dim tmpPass As String = Me.txtUserPass.Text.Trim()

        '判断是否为空
        If String.IsNullOrEmpty(tmpName) Then
            MessageBox.Show("用户名不能为空。", "用户管理")
            Return False
        End If

        If m_state = 1 Then
            '新建则密码也不能为空
            If String.IsNullOrEmpty(tmpPass) Then
                MessageBox.Show("新建用户时必须输入密码。", "用户管理")
                Return False
            End If
        End If

        '如果是新建，则判断用户名是否重复
        If UserNameAlreadyInList(tmpName) And m_state = 1 Then
            Return False
        End If

        Return True
    End Function

    Private Function UserNameAlreadyInList(ByVal n As String) As Boolean
        '在当前的user集合中寻找指定名称
        For Each tmpU As ClsUser In m_userList
            If tmpU.UserName.Equals(n) Then
                Return True
            End If
        Next

        Return False
    End Function

    Private Sub SaveUserToDb()

        Dim tmpDb As ClsUserDbAccess = New ClsUserDbAccess(sysAppInfoConnectionString)
        Dim tmpRet As Int16

        m_saving = True
        m_dirty = False

        '判断是新增还是修改
        If m_state = 1 Then
            tmpRet = tmpDb.InsertUser(m_curUser)

        ElseIf m_state = 2 Then
            tmpRet = tmpDb.UpdateUser(m_curUser)
        End If

        '判断保存结果
        If tmpRet = 0 Then
            MessageBox.Show("保存用户信息出错。", "用户管理")
            '处理错误,将当前浏览的内容填充到列表中，并更新m_curUser内容
            SelectedToUser()
        Else
            '保存成功，如果是新增，则添加到集合列表，如果是修改，则更新集合列表
            If m_state = 1 Then
                '新增
                '更新当前userId
                m_curUser.UserId = tmpRet
                '添加到集合列表
                If m_userList Is Nothing Then
                    m_userList = New List(Of ClsUser)
                End If
                m_userList.Add(m_curUser)
                '添加到listView列表中
                AddUsertoListView(m_curUser)
            Else
                '是修改
                '将当前集合列表中内容更新
                'm_userList.Item(m_userList.IndexOf(m_curUser)).UserName
                '更新listview列表内容
                UserToListView()
            End If
        End If

        '保存完毕后都恢复浏览状态
        m_saving = False
        m_state = 0
        CheckCurrentState()
    End Sub

    Private Sub UserToListView()
        If m_curUser Is Nothing Then
            Return
        End If

        If m_row < 0 Then
            Return
        End If
        Dim curItem As ListViewItem = Me.lstUsers.Items(m_row) 'Me.lstUsers.SelectedItems.Item(m_row)
        curItem.SubItems(0).Text = m_curUser.UserId.ToString
        curItem.SubItems(1).Text = m_curUser.UserName
        curItem.SubItems(2).Text = m_curUser.UserPassword
        curItem.SubItems(3).Text = IIf(m_curUser.UserIfAdmin, "是", "否")

    End Sub

    Private Sub AddUsertoListView(ByVal u As ClsUser)
        If u Is Nothing Then
            Return
        End If

        Dim curItem As ListViewItem = New ListViewItem()
        curItem.SubItems(0).Text = u.UserId.ToString
        curItem.SubItems(1).Text = u.UserName
        curItem.SubItems(2).Text = u.UserPassword
        curItem.SubItems(3).Text = IIf(u.UserIfAdmin, "是", "否")

        Me.lstUsers.Items.Add(curItem)
    End Sub

    Private Sub btnDeleteUser_Click(sender As Object, e As EventArgs) Handles btnDeleteUser.Click
        '删除指定用户
        If m_row < 0 Then
            Return
        End If

        If m_curUser Is Nothing Then
            Return
        End If

        '准备删除
        If MessageBox.Show("你确定要删除这个用户吗？", "用户管理", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
            Return
        End If

        '判断是否是最后一个管理员
        If m_curUser.UserIfAdmin Then
            '判断是否是唯一一个
            If AdminNumber() = 1 Then
                MessageBox.Show("不能删除最后一个管理员，你必须先指定另外一个管理员。", "用户管理")
                Return
            End If
        End If

        '从表中删除
        Dim tmpClsDb As ClsUserDbAccess = New ClsUserDbAccess(sysAppInfoConnectionString)
        If tmpClsDb.DeleteUser(m_curUser) = 0 Then
            MessageBox.Show("删除指定用户时出错。", "用户管理")
            '恢复窗体内容
            m_state = 0
            CheckCurrentState()
        Else
            '删除集合列表内容
            m_userList.RemoveAt(m_row)
            '更新窗体内容
            Me.lstUsers.Items.RemoveAt(m_row)
            m_curUser = Nothing
            '更新编辑状态
            m_state = 0
            m_row = -1
            CheckCurrentState()

        End If
    End Sub

    Private Function AdminNumber() As Int16
        Dim uNumber As Int16 = 0
        For Each tmpU In m_userList
            If tmpU.UserIfAdmin Then
                uNumber += 1
            End If
        Next
        Return uNumber
    End Function
End Class